/*
 * @lc app=leetcode.cn id=42 lang=javascript
 *
 * [42] 接雨水
 */

// @lc code=start
/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {
  const n = height.length;
  const leftMax = new Array(n).fill(0);
  const rightMax = new Array(n).fill(0);
  for (let i = 1; i < n; i++) {
    leftMax[i] = Math.max(height[i - 1], leftMax[i - 1]);
  }
  for (let i = n - 1; i > 0; i--) {
    rightMax[i - 1] = Math.max(height[i], rightMax[i]);
  }
  let res = 0;
  for (let i = 1; i < n - 1; i++) {
    res += Math.max(Math.min(leftMax[i], rightMax[i]) - height[i], 0);
  }
  return res;
};
// @lc code=end
